/**
 * related to main.ui
 * 
 * @Author : chenglm
 * @Timestamp : 2016-12-28
 */
var app = sm("do_App");
var page = sm("do_Page");
var nf = sm("do_Notification");
var openHelper = require("helper/open");
var http = require("helper/http");
var httpSilence = require("helper/httpSilence");
var mallUrl = require("url/mall");
var userUtil = require("helper/user");
var qqmath = require("util/qqmath");
var shareUtil = require("helper/share");

var anim = mm("do_Animation");
var layout = ui("layout");
var listdata = mm("do_ListData");
var listView_list = ui("listView_list");
listView_list.bindItems(listdata);
var alayout_root = ui("alayout_root");
var aLayout_cart = ui("aLayout_cart");
var cartNum = ui("cartNum");
var cartPrice = ui("cartPrice");
var button_order = ui("button_order");
var cartNumLayout = ui("cartNumLayout");

var rootview = ui("$");

var pageNum = 1,totalPages=1;
//andriod返回键
page.on("back", function() {
    app.closePage();
});
/* 头部 */
var hashdata = mm("do_HashData");
var headerAout = ui("layoutHead");
var addheader = headerAout.add("header", "source://view/reuse/header.ui", 0, 0);
//左上角-返回
var headerLeft = ui(addheader+".headerLeft");
headerLeft.on("touch", function() {
    app.closePage()
});
//右上角-
var headerRight = ui(addheader + ".headerRight");
// 右上角添加+图标
var imgNext = ui(addheader + ".imgNext");
imgNext.source = "source://image/common/share.png";
imgNext.visible = true;
var header = ui("header");
header.bindData(hashdata);
hashdata.addData({
    "labelTitle" : '店铺详情'
})
header.refreshData();
var addShare = rootview.add("share","source://view/reuse/share.ui", 0, 0);

var topCategoryUi = ui(alayout_root.add("idTopCategoryUi", "source://view/qshop/detail/cell/categoryCell2.ui", 0, 75));
topCategoryUi.visible = false;
alayout_root.add("categoryGrids", "source://view/qshop/detail/cell/categoryGrid.ui", 0, 75);

var shopId = null;
var categoryId = null;
var hasBus = true;
var cartTotalProduct = 0;

var shareTitle="",shareContent="",shareImage="",shareId;

page.on("loaded", function() {
	var data = page.getData();
	shopId = data.shopId;
	shareId=data.shopId;
	refreshAllData();
});

page.on("result", function(data) {
	updateCartCount();
	if (data != null && data.fromPage != null && data.fromPage=='shopDetail') {
		var data_temp = listdata.getOne(0);
		data_temp.hasCollect = data.hasCollect;
		listdata.updateOne(0, data_temp);
		listView_list.refreshItems();
	}
});
page.on("getCategoryIdToShopDetai", function(data){
	categoryId = data.categoryId;
	pageNum = 0;
	totalPages = 1;
	getNextPageData();
});
page.on("ShopAddToCart", function(data){
	if (hasBus) {
		var productId = data.productId;
		httpSilence.post(mallUrl.url.cart.doAdd, {productId:productId,shopId:shopId, productSpecId:null,quantity:1}, function(data2) {
			if(data2){
				if(data2.cartTotalProduct){
					anim.fillAfter = true;
					anim.alpha({duration:1000,alphaFrom:1,alphaTo:0},"id1");
					anim.transfer({duration:1000,fromX:data.x,fromY:440,toX:0,toY:960},"id2");
					ui("joinImg").source = data.imgJoin;
					layout.animate(anim,function(){
						cartTotalProduct = data2.cartTotalProduct;
						cartNum.text = cartTotalProduct;
						cartPrice.tag = parseFloat(cartPrice.tag) + parseFloat(data.price);
						cartPrice.text = "￥"+qqmath.getDight(cartPrice.tag, 2);
					});	
				}
				if(data2.moreSpect){//多规格商品
					openHelper.open("source://view/mall/product/main.ui",{"id":productId,"fromPage":"qshop"});
				}
			}
		});
	} else {
		nf.toast("暂停营业中");
	}
});
page.on("ShopDetai_isFirstIntoCategory", function(data){
	var temp = listdata.getOne(1);
	listdata.updateOne(1, 
			{
				template : temp.template,
				categoryList : temp.categoryList,
				isFirst : false
			}
	);
	listView_list.refreshItems();
});
var style;
function refreshAllData(){
	pageNum = 1;
	var param = {size:"999",page:pageNum,shopId:shopId};
	http.post(mallUrl.url.shop.buyDetail, param, function(data) {
		shareTitle=data.mallShop.name;
		shareContent=data.mallShop.resume;
		shareImage=data.mallShop.fullLogo;
		style=data.mallShop.style;
		hasBus = data.mallShop.hasBus;
		cartNum.text = data.cartTotalProduct;
		cartTotalProduct = data.cartTotalProduct;
		cartPrice.text = "￥"+data.cartTotalPrice;
		cartPrice.tag = data.cartTotalPrice;
		listView_list.rebound();
		listdata.removeAll();
		listdata.addOne(data.mallShop);
		//圈币抢购
		/*var qbList = [{"firstImg":"http://qquan-hn-crazy.img-cn-shenzhen.aliyuncs.com/mall/20170209114305_256.png@260h_260w_1e_1c","name":"湖北散养土鸡蛋","qbnum":"1000"},{"firstImg":"http://qquan-hn-crazy.img-cn-shenzhen.aliyuncs.com/mall/20170209113515_045.png@260h_260w_1e_1c","name":"湖北土鸡","qbnum":"800"},{"firstImg":"http://qquan-hn-crazy.img-cn-shenzhen.aliyuncs.com/mall/20170209114305_256.png@260h_260w_1e_1c","name":"湖北散养土鸡蛋","qbnum":"600"},{"firstImg":"http://qquan-hn-crazy.img-cn-shenzhen.aliyuncs.com/mall/20170209113515_045.png@260h_260w_1e_1c","name":"湖北土鸡","qbnum":"500"},{"firstImg":"http://qquan-hn-crazy.img-cn-shenzhen.aliyuncs.com/mall/20170209114305_256.png@260h_260w_1e_1c","name":"湖北散养土鸡蛋","qbnum":"400"},{"firstImg":"http://qquan-hn-crazy.img-cn-shenzhen.aliyuncs.com/mall/20170209113515_045.png@260h_260w_1e_1c","name":"湖北土鸡","qbnum":"100"}];
		listdata.addData([{"template":3,"qbList":qbList}]);*/
		listdata.addData([{"template":1,"categoryList":data.categoryList,"isFirst":'true'}]);
		//先显示推荐商品,没有则显示全部商品
		if (data.recommendProList != null && data.recommendProList.length > 0) {
			initProData(data.recommendProList);
		} else {
			totalPages = data.proPage.totalPages;
			initProData(data.proPage.content);
		}
		cartNum.text = data.cartTotalProduct;
		if(cartNum.text > 0) cartNumLayout.visible = true;
		listView_list.refreshItems();
		page.fire("initCategoryData", {"categoryList":data.categoryList});
	});
}

function getNextPageData(){
	pageNum++;
	if (pageNum <= totalPages) {
		var param = {size:"999",page:pageNum,shopId:shopId,categoryId:categoryId};
		http.post(mallUrl.url.shop.buyDetailPro, param, function(data) {
			if (pageNum == 1) {
				listdata.removeRange(2,listdata.getRange(0).length);
			}
			totalPages = data.proPage.totalPages;
			initProData(data.proPage.content)
			listView_list.rebound();
			listView_list.refreshItems();
		})
	} else {
		nf.toast("已是最后一页");
		listView_list.rebound();
	}
}

function initProData(productList){
	if (productList != null) {
		var line = {};			//一行分左右两列
		for (var i=0; i<productList.length; i++) {
			var rec = productList[i];
			if ((i%2) == 0) {
				line.r1 = rec;
			} else {
				line.r2 = rec;
				line.rv = true;
				line.template = 2;
				listdata.addOne(line);
				line = {};
			}
		}
		//可能正好只有左半个
		if (line.r1 != null) {
			line.rv = false;
			line.template = 2;
			listdata.addOne(line);
		}
	}
}

//下拉列表，刷新数据
listView_list.on("pull", function(data){
	//其中state=0：表示开始下拉headerview，；state=1：表示下拉headerview超过headerview的高度，触发一次这个事件；state=2：下拉超过一定值，触发state=1事件后，松手会触发一次这个事件，数据加载完后需要调用rebound方法让header复位
	if (data.state == 2){
		refreshAllData();
	}
});
//设置上拉刷新回调
listView_list.on("push", function(data){
	if (data.state == 2) {
		getNextPageData();
	}
});
listView_list.on("scroll", function(data){
	topCategoryUi.visible = data.firstVisiblePosition > 0;
});

aLayout_cart.on("touch",'' ,300,function(data, e) {
	if(!userUtil.loginToken()){
		openHelper.openLogin();	
	}else{
		if (hasBus) {
			openHelper.open("source://view/qshop/cart/main.ui",{shopId:shopId,style:style});
		} else {
			nf.toast("暂停营业中");
		}
	}
});
button_order.on("touch",'' ,300,function(data, e) {
	if (hasBus) {
		if(cartTotalProduct > 0){
			openHelper.open("source://view/qshop/cart/toOrder.ui",{fromPage:"shop_index",shopId:shopId,style:style},"","pay_product_back");
		}else{
			nf.toast("购物车暂无商品");
		}
	} else {
		nf.toast("暂停营业中");
	}
});

function updateCartCount(){ //更新购物车数量
	if (shopId != null) {
		var param = {shopId:shopId};
		httpSilence.post(mallUrl.url.cart.totalQuantity, param, function(data) {
			cartNum.text = data.totalQuantity;
			cartTotalProduct = data.totalQuantity;
			cartPrice.text = "￥"+data.totalPrice;
			cartPrice.tag = data.totalPrice;
		});
	}
}
headerRight.on("touch", "", 300, function() {
	page.fire("onShare",{showView:"true",shareTitle:shareTitle,shareContent:shareContent,shareId:shareId,shareType:shareUtil.type.Q_SHOP,shareImage:shareImage});
});